const mongoose = require('mongoose')
const glob = require('glob')
const path = require('path')
import {sleep} from '../utils/common'

glob.sync(path.resolve(__dirname, './schema/**/*.js')).forEach(require)

const db = 'mongodb://localhost:27017/react-chat'

mongoose.Promise = global.Promise
mongoose.set('useFindAndModify', false)

module.exports = () => {
  if (process.env.NODE_ENV !== 'production') {
    mongoose.set('debug', true)
  }
  return new Promise((resolve, reject) => {
    mongoose.connect(db, {
      useNewUrlParser: true,
      useCreateIndex: true
    })

    mongoose.connection.on('disconnected', async () => {
      // 链接数据库失败时，10秒后重试
      console.log('db disconnected')
      await sleep(10000)
      mongoose.connect(db)
    })
    mongoose.connection.on('error', async err => {
      console.error(err)
      await sleep(10000)
      mongoose.connect(db)
    })
    mongoose.connection.once('open', () => {
      resolve()
      console.log('connect db successfully!')
    })
  })
}
